package com.mec.web.y2012.ajax;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class YahooSearchGatewayServlet
 */
@WebServlet("/ajax/yahooSearchGateway")
public class YahooSearchGatewayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/*
	 * ref: https://developer.yahoo.com/search/web/V1/webSearch.html
	 * 
	 * ref: https://developer.yahoo.com/blogs/ydn/posts/2010/08/api_updates_and_changes/
	 * 
	 * What a pity! should try other web service sometime later.
	 * date: 2012-04-21
	 * 
	 */
	private static final String YAHOO_SEARCH_URL = 
			"http://search.yahooapis.com/WebSearchService/V1/webSearch?"
			+ "appid=V7x4cD7V34H.Y.QJVPd4uaX23O4Pyc99B_4K.mo1DSY8h5xHIcXCwgfWH8FfFiKlSw--"
			+ "&type=all&"
			;
       
    public YahooSearchGatewayServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = YAHOO_SEARCH_URL + request.getQueryString();
		
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		
		conn.setRequestMethod("GET");
		
		
		//
		response.setStatus(conn.getResponseCode());
		response.setContentType("text/xml");
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String input = null;
		
		ServletOutputStream responseOutput = response.getOutputStream();
		
		//
		while(null != (input = reader.readLine())){
			responseOutput.write(input.getBytes());
			
		}
		//
		responseOutput.close();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	
	private static final Logger logger =  
			Logger.getLogger(YahooSearchGatewayServlet.class);
}
